import socket

# 配置端口号
PORT = 55555  # 服务器的端口号

# 创建TCP/IP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定所有可用的网络接口并指定端口
server_socket.bind(('', PORT))  # 绑定空字符串表示绑定所有网络接口

# 开始监听客户端连接
server_socket.listen(5)
print(f"Server listening on port {PORT}...")

while True:
    # 等待客户端连接
    client_socket, client_address = server_socket.accept()
    print(f"Connection from {client_address}")

    try:
        while True:
            # 接收客户端数据
            data = client_socket.recv(1024)
            if not data:
                break  # 客户端关闭连接，退出循环

            # 打印原始字节数据
            print(f"Raw received data: {repr(data)}")

            # 尝试解码并打印数据
            try:
                print(f"Decoded data: {data.decode('utf-8')}")
            except Exception as e:
                print(f"Decoding error: {e}")

    except Exception as e:
        print(f"Error: {e}")
    finally:
        # 关闭与客户端的连接
        client_socket.close()
        print(f"Connection with {client_address} closed.")

# 关闭服务器套接字（在程序结束时调用）
server_socket.close()
